package com.linln.modules.shopsService.service.impl;

import com.linln.common.data.PageSort;
import com.linln.common.enums.ShopEnum;
import com.linln.common.exception.shopService.ShopException;
import com.linln.common.utils.DistanceUtil;
import com.linln.common.utils.PathMappingUtil;
import com.linln.common.utils.UUIDUtil;
import com.linln.common.vo.JsonResult;
import com.linln.common.vo.PageResult;
import com.linln.modules.shopsService.domain.Shops;
import com.linln.modules.shopsService.repository.ShopsRepository;
import com.linln.modules.shopsService.service.ShopsService;
import com.linln.modules.system.domain.User;
import com.linln.modules.system.enums.ConstantEnum;
import com.linln.modules.system.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zsc
 * @date 2020/11/19
 */
@Service
public class ShopsServiceImpl implements ShopsService {

    @Autowired
    private ShopsRepository shopsRepository;

    @Autowired
    private UserRepository userRepository;


    @PersistenceContext
    EntityManager entityManager;

    @Value("${server.ip}")
    private String ip;


    /**
     * 根据ID查询数据
     *
     * @param id 主键ID
     */
    @Override
    @Transactional
    public Shops getById(String id) {
        return shopsRepository.findById(id).orElse(null);
    }

    /**
     * 获取分页列表数据
     *
     * @param example 查询实例
     * @return 返回分页数据
     */
    @Override
    public Page<Shops> getPageList(Example<Shops> example) {
        // 创建分页对象
        PageRequest page = PageSort.pageRequest("shopName", Sort.Direction.DESC);
        return shopsRepository.findAll(example, page);
    }

    /**
     * 添加或修改
     *
     * @param shops  实体对象
     * @param userId 新店长userId
     * @param file   文件
     * @param flag   添加还是修改  真为修改 假为添加
     * @return
     * @throws Exception
     */
    @Override
    @Transactional
    public Shops save(Shops shops, Long userId, MultipartFile file, Boolean flag) throws Exception {
        Long roleId = Long.valueOf(ConstantEnum.STOREMANAGER.getValue());
        //flag true 修改 false 添加
        if (flag) {
            //店铺原有店长
            if (userId != null) {
                Map<String, Object> manager = getManager(shops.getShopId(), Long.valueOf(ConstantEnum.STOREMANAGER.getValue()));
                //新店长和老店长id 相同则代表无修改店长
                if (!userId.toString().equals(manager.size() == 0 ? "" : manager.get("id").toString())) {
                    //查询用户是否已关联了店铺
/*                    int count = shopsRepository.searchShopUser(userId);
                    if (count > 0) {
                        throw new ShopException("人员已经关联店铺");
                    }*/
                    int count = shopsRepository.searchShopBoss(userId);
                    //如果新店长和原店长不是同一人作修改操作
                    //删除原有店长角色信息
                    if (manager.size() != 0) {
                        if (count < 2) {
                            shopsRepository.delShopRole(Long.valueOf(manager.get("id").toString()), Long.valueOf(ConstantEnum.STOREMANAGER.getValue()));
                        }
                        //删除用户与店铺的关联信息
                        shopsRepository.delShopUser(manager.get("shop_user_id").toString());
                    }
                    //创建店长角色
                    if (count < 1) {
                        shopsRepository.createUserRole(userId, roleId);
                    }
                    //用户关联店铺
                    shopsRepository.addShopUser(UUIDUtil.randomUUID32(), shops.getShopId(), userId,
                            new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                }
            }
        } else {
            if (userId != null) {
/*                if (shopsRepository.searchShopUser(userId) > 0) {
                    throw new ShopException("人员已经关联店铺");
                }*/
                int count = shopsRepository.searchShopBoss(userId);
                if (count < 1) {
                    shopsRepository.createUserRole(userId, roleId);
                }
                //用户关联店铺
                shopsRepository.addShopUser(UUIDUtil.randomUUID32(), shops.getShopId(), userId,
                        new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            }
        }

        //保存图片操作
        if (file != null) {
            shops.setShopPicture(PathMappingUtil.saveImg(PathMappingUtil.IMGPATH, PathMappingUtil.IMGPATHMAPPING, file));
        }
        return shopsRepository.save(shops);
    }


    /**
     * 添加店员并且添加角色
     *
     * @param shopsId
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public JsonResult addShopUser(String shopsId, Long userId) {
        //查询店铺用户是否存在
        int count = shopsRepository.searchShopUser(userId);
        if (count == 0) {
            //添加角色系列操作
            Long roleId = Long.valueOf(ConstantEnum.CLEAK.getValue());
            shopsRepository.createUserRole(userId, roleId);
            //添加时间
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            Date now = new Date();
            String time = sdf.format(now);
            return shopsRepository.addShopUser(UUIDUtil.randomUUID32(), shopsId, userId, time) == 1 ? JsonResult.ok() : JsonResult.error();
        } else {
            return JsonResult.error("该人员已经是店铺人员");
        }

    }


    /**
     * 查看所有店铺人员
     *
     * @param page
     * @param limit
     * @param shopsId
     * @return
     */
    @Override
    public PageResult<Map<String, String>> shopUserPage(Integer page, Integer limit, String shopsId) {
        int count = shopsRepository.findAllShopCount(shopsId);
        return new PageResult<>(shopsRepository.findAllShop(page, limit, shopsId), count);
    }


    /**
     * @param lon
     * @param lat
     * @return
     */
    private List<Map<String, String>> setDistance(String lon, String lat, Page<Map<String, String>> page) {
        List<Map<String, String>> content = page.getContent();
        List<Map<String, String>> shopMap = new ArrayList<>();
        //设置距离
        content.forEach(item -> {
                    HashMap<String, String> map = new HashMap<>(item);
                    double distance = DistanceUtil.distance(Double.parseDouble(lon), Double.parseDouble(lat), new Double(map.get("longitude")), new Double(map.get("dimension")));
                    map.put("distance", String.valueOf(distance));
                    map.put("shop_picture", ip + map.get("shop_picture"));
                    shopMap.add(map);
                }
        );
        return shopMap;
    }

    /**
     * 更具电话查询用户
     *
     * @param phone
     * @return
     */
    @Override
    public User getByPhone(String phone) {
        return userRepository.findByPhone(phone);
    }

    /**
     * 删除店铺用户
     *
     * @param shopUserId
     * @param userId
     * @return
     */
    @Override
    @Transactional
    public void delShopUser(String shopUserId, Long userId) {
        shopsRepository.delShopRole(userId, Long.valueOf(ConstantEnum.CLEAK.getValue()));
        shopsRepository.delShopUser(shopUserId);
    }

    /**
     * 位置
     *
     * @param parentId
     * @param areaId
     * @return
     */
    @Override
    public List<Map<String, Object>> getAreaData(String parentId, String areaId) {
        List<Map<String, Object>> data = shopsRepository.getAreaData(parentId, areaId);
        return data;
    }

    /**
     * 获取店长
     *
     * @param shopId 店铺id
     * @param roleId 角色id
     * @return
     */
    @Override
    public Map<String, Object> getManager(String shopId, Long roleId) {
        return shopsRepository.getManager(shopId, roleId);
    }

    /**
     * 删除店铺
     *
     * @param shopId
     * @return
     */
    @Override
    @Transactional
    public void deleteShop(String shopId) {
        //普通店员id
        List<String> shopIds = shopsRepository.getAllShop(shopId);
        //店长
        Map<String, Object> manager = shopsRepository.getManager(shopId, Long.valueOf(ConstantEnum.STOREMANAGER.getValue()));

        //删除店铺(逻辑)
        shopsRepository.deleteFlagById(shopId);
        //删除店铺所有人员
        shopsRepository.delShopAllUser(shopId);
        //删除店长角色
        if (manager.size() > 0) {
            Long managerId = Long.valueOf(manager.get("id").toString());
            shopsRepository.delShopRole(managerId, Long.valueOf(ConstantEnum.STOREMANAGER.getValue()));
        }
        //删除所有店员角色
        if (shopIds.size() > 0) {
            shopsRepository.delAllShopRole(shopIds);
        }
    }

    @Override
    public List<Map<String, Object>> getShopType() {
        return shopsRepository.getShopType();

    }

    @Override
    public JsonResult saveVerificationImgByBase64(String base64, int type) {
        try {
            String path = "";
            String mapping = "";
            switch (ShopEnum.getByType(type)) {
                case BUSINESSLICENSE:
                    path = PathMappingUtil.BUSINESSLICENSEPATH;
                    mapping = PathMappingUtil.BUSINESSLICENSEMAPPING;
                    break;
                case PHYSICALSTORE:
                    path = PathMappingUtil.PHYSICALSTOREPATH;
                    mapping = PathMappingUtil.PHYSICALSTOREMAPPING;
                    break;
                case CONSTRUCTIONWORKSHOP:
                    path = PathMappingUtil.CONSTRUCTIONWORKSHOPPATH;
                    mapping = PathMappingUtil.CONSTRUCTIONWORKSHOPMAPPING;
                    break;
                case TECHNICIANCONSTRUCTION:
                    path = PathMappingUtil.TECHNICIANCONSTRUCTIONPATH;
                    mapping = PathMappingUtil.TECHNICIANCONSTRUCTIONMAPPING;
                    break;
            }
            String imgPath = PathMappingUtil.saveImg(path, mapping, PathMappingUtil.base64ToMultipart(base64));
            return JsonResult.ok("保存核销图片成功").put("data", new HashMap<String, Object>() {{
                put("imgPath", imgPath);
            }});
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonResult.error().put("msg", "保存核销图片失败");
    }

    @Override
    public List<Map<String, Object>>  getByUserShops(Long id) {
        return shopsRepository.getShopsByUser(id);
    }

    @Override
    public Map<String, Object>  getByUserShop(Long id) {
        return shopsRepository.getShopByUser(id);
    }

    @Override
    public String getAddressbyAreaId(String address) {
        //定位省获取索引位置 ，再截取
        int index = address.indexOf("省");
        String sheng = address.substring(0, index + 1);
        int index2 = address.indexOf("市");
        String shi = "";
        if(index2!=-1) {
            shi = address.substring(index + 1, index2 + 1);
        }else {
            shi = sheng;
        }
        return shopsRepository.getAddressbyAreaId(shi);
    }

    @Override
    public String getShopTypeName(String[] ids) {
        List<Map<String, Object>> mapList = shopsRepository.getShopType();
        StringBuilder names = new StringBuilder();
        for (int i = 0; i < ids.length; ++i) {
            for (Map map : mapList) {
                if (ids[i].equals(map.get("value").toString())) {
                    names.append(map.get("name")+",");
                }
            }
        }
        String shopTypeName = "";
        if(names.length()>0){
            shopTypeName = names.substring(0,names.length()-1);
        }
        return shopTypeName;
    }

    public String shopNameById(String shopId){
        return shopsRepository.getShopNameByShopId(shopId);
    }

    @Override
    public List<Shops> getByIds(List<String> ids) {
        return shopsRepository.findByShopIdIn(ids.toArray(new String[ids.size()]));
    }

    @Override
    public void saveShopDetails(Shops shops) {
        shopsRepository.save(shops);
    }
}
